$(function () {
	var content = "subscribe";
	var dataCount = 0;
	var hisCount = 0;
	var subCount = 0;
	var myTheCount = 0;
	var myComCount = 0;
	var page = 1;
	var tableName = "Subscribe";
	var backData = false;
	var color = ["lightblue","lightcoral","lightglod"];
	var totalHeight = $("#data-content")[0].scrollHeight + 44;
	// 让 header 的 button 居中
	function btnCenter() {
		var vw = ($(window).width() - 107) / 2;
		var fw = ($(window).width() - 160) / 2;
		var rw = ($(window).width() - $(".remind").width()) / 2;
		$("header .btn-group").css("left", vw);
		$(".footerNav").css("left", fw);
		$(".remind").css("left", rw);
	};
	btnCenter();
	$(window).resize(function () {
		btnCenter();
	});
	$("header .btn-group a").on("click", function () {
		$(this).css({
			backgroundColor: "white",
			color: "lightblue"
		}).siblings().css({
			backgroundColor: "lightblue",
			color: "white"
		});
		if ($(this).attr("id") == "history") {
			$(".footerNav a").removeClass("disabled").removeClass("footerA");
			$(".footerNav a").eq(0).addClass("lightBgc");
			content = "history";
		} else {
			$(".footerNav a").removeClass("lightBgc").addClass("disabled").addClass("footerA");
		}
	});

	$("#goback").on("click", function () {
		history.go(-1);
	});

	// 日期格式
	function formatDate(time){
		time = new Date(time);
		var am = "";
		var y = time.getFullYear();		
		var M = time.getMonth()+1;
		var d = time.getDate();
		var h = time.getHours();
		var m = time.getMinutes();
		M = M<10 ? "0"+M : M;
		d = d<10 ? "0"+d : d;
		h = h<10 ? "0"+h : h;
		m = m<10 ? "0"+m : m;
		if(h<=12){
			am = "上午";
		}else{
			am = "下午"
		}
		return y+"-"+M+"-"+d+" "+am+" "+h+":"+m;
	}
	function fs(){
//		console.log($(".sectionTime").text());
		var time = formatDate($(".sectionTime").text());
	
	}
//	function formatHtml(){
//		var htmls = [];
//		
//		for(var i=0;i<resData.data.length;i++){
//			if(resData.data.theme_id){
//				htmls.push(resData.data[i].theme.info.content);
//			}else if(resData.data.comment_id){
//				htmls.push(resData.data[i].comment_info.content);
//			}else{
//				htmls.push(resData.data[i].content)
//			}
//		}
//		console.log("ooo"+htmls);
//		$(".mc").each(function(index){
//			$(this).html(htmls[index]);
//		})
//		
//	}
	
	
	$("#delete").on({
		mousedown: function () {
			$(this).css("color", "#999")
		},
		mouseup: function () {
			$(this).css("color", "white");
		},
		click: function () {
			if (!$(".sLeft").data("open")) {
				$(".sLeft").data("open", true).css("flex-basis", "15%").find("span").fadeIn();
			} else {
				$(".sLeft").data("open", false).css("flex-basis", 0).find("span").hide();
			}
			$(".sRight").data("open", false).css("flex-basis", 0).find("span").hide();
		}
	})

	$("#data-content").on("click", ".sLeft", function () {
		$(this).css("flex-basis", 0).find("span").hide();
		$(this).parents("li").find(".sRight").data("open", true).css("flex-basis", "20%").find("span").fadeIn();
	});

	// 回到顶部事件
	$("#backTop").click(function (event) {
		$("html,body").animate({
			scrollTop: 0
		}, 500)
	});
	// 到底部按钮事件
	$("#backBottom").click(function () {
		var vh = $("#data-content")[0].scrollHeight - $(window).height() + 44;
		$("html,body").animate({
			scrollTop: vh
		}, 500);
	});

	/* *************** 请求********************** */

	// 删除记录请求
	$("#data-content").on("click", ".sRight", function (){
		var $this = $(this);
		var id = $(this).parents("li").data("history");
		console.log(id);
		var data = {
			id: id,
			tableName: tableName
		};
		if (confirm("确定删除?")) {
			$.ajax({
				type: "post",
				url: "comment/delete",
				data: data,
				async: true
			}).done(function (resData, status, jqXHR) {
				console.log(status);
				if (resData.code == 1) {
					alert(resData.message);
					$(".dataCount").text($(".dataCount").text()-1);
					$this.parents(".moveTheme").slideUp();
					if (tableName == 'History') {
						var array = JSON.parse(window.localStorage.getItem('history_list'));
						for (var i = 0; i < array.length; i++) {
							if (array[i] == id) {
								array.splice(i, 1);
							}
						}
						window.localStorage.setItem('history_list', JSON.stringify(array));
					}
				} else {
					alert(resData.message);
				}
			}).fail(function () {
				alert("因为未知的错误，删除失败");
			});
		} else {
			$(this).data("open", false).css("flex-basis", "0").find("span").hide();

		}
	});

	var htmlStr = "";
	var show1 = false;
	// 请求页面默认数据(订阅的记录)
	$.ajax({
		type: "get",
		url: "/subscribe",
		async: true
	}).done(function (resData, status, jqXHR) {
//		console.log(resData);
		if (resData.data.length) {			
			htmlStr = template("mainTemplate", resData);
//			console.log(resData);
			$("#data-content").html(htmlStr).slideDown();
//			formatHtml();
			
			var htmls = [];
			for(var i=0;i<resData.data.length;i++){
				if(resData.data[i].theme_id){
					htmls.push(resData.data[i].theme_info.content);
				}else if(resData.data[i].comment_id){
					htmls.push(resData.data[i].comment_info.content);
				}else{
					htmls.push(resData.data[i].content)
				}
			}
//			console.log("ooo"+htmls);
			$(".mc").each(function(index){
				$(this).html(htmls[index]);
			})
			
			htmlStr = $("#data-content").html();
			fs();
			subCount += resData.data.length;
			var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
			$("#data-content ul").append(loading);
			$(".dataCount").text(subCount);
			$("body").css("overflow", "scroll")
			if(resData.total>page){
				show1 = true;
				$(".loading").show();
			}else{
				$(".loading").hide()
			}
			} else {
			htmlStr = "<p class='remind'>没有订阅的历史记录</p>";
			$("#data-content").html(htmlStr).show();
			
			btnCenter();
			$("body").css("overflow", "hidden");
		}
	}).fail(function (jqXHR, status, error) {
		htmlStr = "<p class='remind'>系统出现未知的错误</p>";
		$("#data-content").html(htmlStr);
		btnCenter();
		$("body").css("overflow", "hidden");

	});
	
	// 点击订阅按钮显示页面第一次请求回来的数据(如果有的话)
	$("#subscribe").on("click", function () {
		$(this).addClass("lightBgc").siblings().removeClass("lightBgc");
		
		tableName = "Subscribe"
		$("#data-content").html(htmlStr);
//		formatHtml();
		fs();
		if(show1){
				var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
				$("#data-content ul").append(loading);
		}
			$(".dataCount").text(subCount);
		btnCenter();
		content = "subscribe";

	});
	var readHtml = "";
	// 点击历史按钮请求注目(浏览)的历史记录
	var show2 = false;
	$("#history").on("click", function () {
		var table = $('#data-content li').data('table');
		tableName = "History";
		console.log(show2);
		$(this).addClass("lightBgc").siblings().removeClass("lightBgc");
		
		if (readHtml) {

			$("#data-content").html(readHtml);
			
				
			
//			formatHtml();
			fs();
			if(show2){
				var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
				$("#data-content ul").append(loading);
			}
			
			$(".dataCount").text(hisCount);
			btnCenter();
		} else {
			var historyarray = JSON.parse(window.localStorage.getItem("history_list"));

			var data = {
				history_list: historyarray
			};
//			console.log(historyarray);
			$.ajax({
				type: "get",
				url: "/users/history",
				async: true,
				data: data
			}).done(function (resData, status, jqXHR) {
				if (resData.data.length) {
					readHtml = template("mainTemplate", resData);
					console.log(resData);
					$("#data-content").html(readHtml).slideDown();
					fs();
					
					var htmls = [];
					for(var i=0;i<resData.data.length;i++){
						if(resData.data[i].theme_id){
							htmls.push(resData.data[i].theme.info.content);
						}else if(resData.data[i].comment_id){
							htmls.push(resData.data[i].comment_info.content);
						}else{
							htmls.push(resData.data[i].content)
						}
					}
					$(".mc").each(function(index){
						$(this).html(htmls[index]);
					})
//					console.log("ooo"+htmls);
					
					readHtml = $("#data-content").html();
					
//					formatHtml();
					var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
					$("#data-content ul").append(loading);
					
					hisCount += resData.data.length;
					$(".dataCount").text(hisCount);
					$("body").css("overflow", "scroll")
//					$(".loading").show();
					if (resData.list != undefined) {
						console.log(resData.list);
						// console.log(JSON.stringify(resData.list));
						window.localStorage.setItem('history_list', JSON.stringify(resData.list));
					}
					totalHeight = $("#data-content")[0].scrollHeight + 44;
					if(resData.total>page){
//						alert(1);
						
						show2 = true;
						$(".loading").show();
					}else{
						$(".loading").hide()
					}
				} else {
					readHtml = "<p class='remind'>没有更多的浏览历史记录</p>";
					$("#data-content").html(readHtml);
					btnCenter();
					$("body").css("overflow", "hidden");
				}
			}).fail(function (jqXHR, status, error) {
				readHtml = "<p class='remind'>系统出现未知的错误</p>";
				$("#data-content").html(readHtml);
				btnCenter();
				$("body").css("overflow", "hidden");

			});
		}

	});
	var show3 = false;
	// 点击注目按钮显示浏览历史记录
	$(".readWC").on("click", function () {
		tableName = "History";
		$(this).addClass("lightBgc").siblings().removeClass("lightBgc");
		
		$("#data-content").html(readHtml);
//		formatHtml();
//		var htmls = [];
//				for(var i=0;i<resData.data.length;i++){
//					if(resData.data.theme_id){
//						htmls.push(resData.data[i].theme.info.content);
//					}else if(resData.data.comment_id){
//						htmls.push(resData.data[i].comment_info.content);
//					}else{
//						htmls.push(resData.data[i].content)
//					}
//				}
//				$(".mc").each(function(index){
//					$(this).html(htmls[index]);
//				})
//		
		fs();
		if(show3){
			var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
			$("#data-content ul").append(loading);
		}
		
		$(".dataCount").text(hisCount);
		content = "history";
		btnCenter();
	})
	// 点击回复按钮显示回复的历史记录
	var replyHtml = "";
	$(".replyWC").on("click", function () {
		var table = $('#data-content li').data('table');
		tableName = "Comment";
		$(this).addClass("lightBgc").siblings().removeClass("lightBgc");
		
		content = "reply";
		if (replyHtml) {
			$("#data-content").html(replyHtml);
//			formatHtml();
			fs();
			
			
			
			var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
			$("#data-content ul").append(loading);
			$(".dataCount").text(myComCount);
			btnCenter();
		} else {
			$.ajax({
				type: "get",
				url: "/mycomment",
				async: true
			}).done(function (resData, status, jqXHR) {
				if (resData) {
					replyHtml = template("mainTemplate", resData);
					console.log(resData);
					$("#data-content").html(replyHtml).slideDown();
					fs();
					
					var htmls = [];
					for(var i=0;i<resData.data.length;i++){
						if(resData.data[i].theme_id){
							htmls.push(resData.data[i].theme_info.content);
						}else if(resData.data[i].comment_id){
							htmls.push(resData.data[i].comment_info.content);
						}else{
							htmls.push(resData.data[i].content);
						}
					}
					
					
					$(".mc").each(function(index){
						$(this).html(htmls[index]);
					})
					
					
					
//					formatHtml();
					myComCount += resData.data.length;
					$(".dataCount").text(myComCount);
					var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
					$("#data-content ul").append(loading);
					$("body").css("overflow", "scroll")
					if(resData.total>page){
						show3 = true;
						$(".loading").show();
					}else{
						$(".loading").hide();
					}

						$("#data-content .badge").each(function(){
							var mr = Math.floor(Math.random()*3);
							$(this).css("background-color",color[mr]);
						});
					replyHtml = $("#data-content").html();
				} else {
					replyHtml = "<p class='remind'>没有更多的回复历史记录</p>";
					$("#data-content").html(replyHtml);
					$("body").css("overflow", "hidden");
					btnCenter();

				}
			}).fail(function (jqXHR, status, error) {
				replyHtml = "<p class='remind'>系统出现未知的错误</p>";
				$("#data-content").html(replyHtml);
				btnCenter();
				$("body").css("overflow", "hidden");
			});
		}
		btnCenter();
	});

	// 点击吐槽按钮显示吐槽过的记录
	var postHtml = "";
	var show4 = false;
	$(".postWC").on("click", function () {
		tableName = "Theme";
		content = "history";
		$(this).addClass("lightBgc").siblings().removeClass("lightBgc");
		if (postHtml) {
			$("#data-content").html(postHtml);
			fs();
			
				
			
//			formatHtml();
			if(show4){
				var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
				$("#data-content ul").append(loading);
			}
			$(".dataCount").text(myTheCount);
			btnCenter();
		} else {
			$.ajax({
				type: "get",
				url: "/mytheme",
				async: true
			}).done(function (resData, status, jqXHR) {
				if (resData) {
					postHtml = template("mainTemplate", resData);
					console.log(resData);
					$("#data-content").html(postHtml).slideDown();
					fs();
					
					var htmls = [];
					for(var i=0;i<resData.data.length;i++){
						if(resData.data[i].theme_id){
							htmls.push(resData.data[i].theme_info.content);
						}else if(resData.data[i].comment_id){
							htmls.push(resData.data[i].comment_info.content);
						}else{
							htmls.push(resData.data[i].content)
						}
					}
					$(".mc").each(function(index){
						$(this).html(htmls[index]);
					})
					postHtml = $("data-content").html();
					
					
//					formatHtml();
					var loading = "<footer class='loading'><div><span class='glyphicon glyphicon-cloud-upload iconM'></span><span class=loadText'>上拉加载</span></div></footer>";
					$("#data-content ul").append(loading);
					myTheCount += resData.data.length;
					$(".dataCount").text(myTheCount);
					$("body").css("overflow", "scroll")
					if(resData.total>page){
						show4 = true;
						$(".loading").show();
					}else{
						$(".loading").hide();
						
					}
				
				} else {
					postHtml = "<p class='remind'>没有更多的吐槽历史记录</p>";
					$("#data-content").html(postHtml);
					btnCenter();
					$("body").css("overflow", "hidden");
				}
			}).fail(function (jqXHR, status, error) {
				postHtml = "<p class='remind'>系统出现未知的错误</p>";
				$("#data-content").html(postHtml);
				btnCenter();
				$("body").css("overflow", "hidden");
			});
		}


	});

	$("#data-content").on("click",".sCc",function(){
//		console.log($(this).data("history"));
		$(this).find(".badge").fadeOut();
		console.log(tableName);
		if(tableName == "Comment"){
			// console.log("/theme.html?id="+$(".moveTheme").data("comment") + "&com_id=" + $(".moveTheme").data("history"));
			location.href = "/theme.html?id="+$(this).parents(".moveTheme").data("comment") + "&com_id=" + $(this).parents(".moveTheme").data("history");
		}else{
			location.href = "/theme.html?id="+$(this).parents(".moveTheme").data("history");
		}
		
	});
	

	

	
	// var dataCount = 0;
	// 上拉刷新
	var timer;
	$(window).scroll(function () {
		clearTimeout(timer);
		$(".shortcutBtn").fadeIn();
		timer = setTimeout(function () {
			$(".shortcutBtn").fadeOut();
		}, 1000);
		var vx = $(window).height();
		var ws = $(window).scrollTop();
		var total = vx + ws;
//		console.log(total + 'total');
//		console.log(totalHeight + 'totalHeight');
		if (total >= totalHeight - 10 &&!backData) {
			backData = true;
			$(".loading").css({
				backgroundImage: "url(../images/loading_010.gif)",
				backgroundRepeat: "no-repeat",
				backgroundPosition: "50% 0"
			}).find("div").hide();
			page = page + 1;
			var data = {
				user: $.cookie("wcID"),
				content,
				dataCount,
				page
			}
			$.ajax({
				type: "get",
				url: "/newHistory",
				async: true,
				data: data
			}).done(function (resData) {
				console.log(resData);
				if (resData.total>page){
					htmlStr = template("mainTemplate", resData);
					$("#data-content").append(htmlStr);
					totalHeight = $("#data-content")[0].scrollHeight + 44;
					dataCount += dataCount + resData.length;
					$(".dataCount").text(dataCount);
					$(".loading").appendTo($("#data-content ul"));
					$(".loading").css("background-image", "").find("div").show().find(".iconM").show().next().text("上拉加载");
					backData = false;
				} else {
					$(".loading").css("background-image", "").find("div").show().html("<p>没有更多的数据</p>");
				}
			}).fail(function (jqXHR, status, error) {
				$(".loading").css("background-image", "").find("div").show().html("<p><span class='glyphicon glyphicon-remove'></span>&nbsp;加载失败</p>");
			})
		}
	});




});